# -*-coding:utf-8-*-

import urllib
import json, pymongo
from tornado.httpclient import HTTPClient, HTTPRequest
from daos.apps import AppsDao


def url_compose(path, query=None):
    if query is None:
        return 'https://api.weixin.qq.com/%s' % (path)
    else:
        return 'https://api.weixin.qq.com/%s?%s' % (path, query)


def http_get(path, query=None):
    url = url_compose(path, query)
    http_client = HTTPClient()
    return http_client.fetch(url, raise_error=False)


def __http_method(method, path, body=None, query=None):
    url = url_compose(path, query)
    if body is not None:
        body = json.dumps(body)
    http_request = HTTPRequest(url, method=method, body=body)
    http_client = HTTPClient()
    return http_client.fetch(http_request, raise_error=False)


def http_post(path, body=None, query=None):
    return __http_method('POST', path, body, query)


def http_put(path, body=None, query=None):
    return __http_method('PUT', path, body, query)


def http_delete(path, body=None, query=None):
    return __http_method('DELETE', path, body, query)


'''
https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
'''

appkey = 'CA7E0BE302DF22F9CF4315BDCF66B62D'  # {"errcode":48001,"errmsg":"api unauthorized hint: [MKzATA0696a458!]"}
appkey = '403DB206089258FBB529B861AB768D59'


def get_access_token():
    db = pymongo.MongoClient().get_database('bora')
    app = AppsDao(db).get_app(appkey)
    query = 'grant_type=client_credential&appid=%s&secret=%s' % (app.get_wx_mp_app_id(), app.get_wx_mp_secret())
    response = http_get('cgi-bin/token', query)
    response = json.loads(response.body)
    print response
    return response['access_token']


'''
 https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN
'''

menu = {
    'button': [
        {
            'type': 'view',
            'name': 'Demo',
            'url': 'http://wx.iot.microembed.net/mp/auth?appkey=%s&redirect_uri=%s' % (appkey, urllib.quote_plus(
                'http://wx.iot.microembed.net')),
        }
    ]
}


def create_menu():
    access_token = get_access_token()
    print access_token
    query = 'access_token=%s' % access_token
    response = http_post('cgi-bin/menu/create', menu, query)
    print response.body


if '__main__' == __name__:
    # get_access_token()
    # print menu
    create_menu()
